package com.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.app.common.CalculateDistance;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.BusinessService;
import com.app.service.CommentService;
import com.app.service.IntegralRecordService;
import com.app.service.UserService;
import com.app.utils.CommonHelp;
import com.app.utils.StringTool;
import com.app.utils.TokenUtils;
import com.app.vo.ActivityVo;
import com.app.vo.BusinessDataVo;
import com.app.vo.BusinessVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商家信息
 *
 * @author 16693103420
 * @since 2024-01-22
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, BusinessModel> implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private UserBusinessMapper userBusinessMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private InviteRecordMapper inviteRecordMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private IntegralRecordService integralRecordService;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private DistributionRecordsMapper distributionRecordsMapper;
    @Autowired
    private CommentService commentService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private MessageBoxMapper messageBoxMapper;
    @Autowired
    private UserService userService;

    //查询商家列表
    @Override
    public BusinessVo getBusinessList(AdminUserModel user, Integer page, Integer limit, String keywords, Integer areaId, Integer status) {
        Integer roleId = user.getRoleId();
//        int offset = (page - 1) * limit;
//        List<BusinessModel> businessList= businessMapper.selectPageTwoTables(offset,limit,keywords,areaId,status);
//添加权限字段被改掉的代码
        Page<BusinessModel> page1 = new Page<>(page, limit);
        QueryWrapper<BusinessModel> qw = new QueryWrapper<>();
        if (StringTool.isNotEmpty(keywords)) {
            qw.like("business_name", keywords).or().like("business_phone", keywords);
        }
        if (user.getRoleId() == 3) {
            qw.eq("city_id", areaId).or().eq("city_id", user.getAreaId());
        }
        if (user.getRoleId() == 4) {
            qw.eq("area_id", areaId).or().eq("area_id", user.getAreaId());
        }
        if (roleId == 2) {//商家管理员登录只能看到只记得的商家信息
            qw.eq("id", user.getBusinessId());
        }
        if(status!=null)
        {
            qw.eq("business_status",status);
        }
        qw.orderByDesc("create_time");
        Page<BusinessModel> businessPage = businessMapper.selectPage(page1, qw);
        QueryWrapper<CategoryModel> categoryModelQueryWrapper = new QueryWrapper<>();
        categoryModelQueryWrapper.eq("pid", 10);
        categoryModelQueryWrapper.eq("status", 1);
        List<CategoryModel> categoryModelList = categoryMapper.selectList(categoryModelQueryWrapper);
        List<BusinessModel> businessModels = businessPage.getRecords();
        for (BusinessModel businessModel : businessModels) {
            for (CategoryModel categoryModel : categoryModelList) {
                if (businessModel.getType().equals(categoryModel.getId())) {
                    businessModel.setTypeText(categoryModel.getName());
                }
            }
            if (businessModel.getBusinessStatus() == 1) {
                businessModel.setBusinessStatusText("营业中");
            } else {
                businessModel.setBusinessStatusText("未营业");
            }
            //构建areaText字段
            String areaText;
            String businessAreaId = businessModel.getAreaId();
            QueryWrapper<AreaModel> areaQW = new QueryWrapper<>();
            areaQW.eq("area_id", businessAreaId);
            AreaModel areaModel = areaMapper.selectOne(areaQW);
            areaText = areaModel.getArea();
            if (businessModel.getCityId() != null) {
                CityModel cityModel = cityMapper.selectOne(new QueryWrapper<CityModel>()
                        .eq("city_id", businessModel.getCityId()));
                String city = cityModel.getCity();

                ProvinceModel provinceModel = provinceMapper.selectOne(new QueryWrapper<ProvinceModel>()
                        .eq("province_id", cityModel.getProvinceId()));

                areaText = provinceModel.getProvince() + "\\" + city + "\\" + areaText;
            }
            businessModel.setAreaText(areaText);
            //文件id转义
            List<String> urlList = new ArrayList<>();
            if (StrUtil.isNotBlank(businessModel.getFileId())) {
                String fileIdArr = businessModel.getFileId();
                String[] split = fileIdArr.split(",");
                for (String fileIds : split) {
                    int fileId = Integer.parseInt(fileIds);
                    FileModel fileModel = fileMapper.selectById(fileId);
                    if (fileModel != null && fileModel.getFileType() != null) {
                        if (fileModel.getFileType() == 1) {
                            urlList.add(fileModel.getUrl());
                        }
                    }
                }
            }
            businessModel.setUrlList(urlList);
        }
        BusinessVo businessVo = new BusinessVo();
        businessVo.setList(businessPage.getRecords());
        businessVo.setCount(Math.toIntExact(businessPage.getTotal()));
        return businessVo;
    }


    /**
     * get is pick活动列表
     *
     * @param page           第页
     * @param limit          限制
     * @param classification 分类
     * @param activityName   活动名称
     * @param type           类型
     * @param sort           排序
     * @param latitude       纬度
     * @param longitude      经度
     * @return {@link ActivityVo}
     */
    public ActivityVo getIsPickActivityList(Integer page, Integer limit, Integer classification, String activityName,Integer type,
                                            Integer sort,Double latitude,Double longitude ){
        IPage<ActivityModel> pa=new Page<>(page,limit);
        IPage<ActivityModel> businessModelList=businessMapper.getActivityList(pa,classification,activityName,type,sort);
        if(CollectionUtil.isNotEmpty(businessModelList.getRecords()))
        {
            if(sort!=null&&sort==2)
            {
                for (ActivityModel model:businessModelList.getRecords()
                ) {
                        model.setDistance(CalculateDistance.haversine(latitude,longitude,model.getLatitude(),model.getLongitude()));
                }
                // 使用Comparator.comparing来创建一个比较器，然后进行排序
                businessModelList.getRecords().sort(Comparator.comparing(ActivityModel::getDistance));
            }
        }
        ActivityVo activityVo=new ActivityVo();
        activityVo.setList(businessModelList.getRecords());
        activityVo.setCount((int) businessModelList.getTotal());
        return activityVo;
    }


    //用户查询商家列表
    @Override
    public BusinessVo getUserBusinessList(Integer page, Integer limit, String businessName, String areaId, Integer type, Double longitude, Double latitude, Integer sort, Integer classification, HttpServletRequest request) {
        Page<BusinessModel> page1 = new Page<>(page, limit);

        Page<BusinessModel> businessPage = businessMapper
                .queryMerchantsForASpecificActivity(page1,classification,businessName,type,longitude,latitude);
        List<BusinessModel> businessList = businessPage.getRecords();
        for (BusinessModel businessModel : businessList) {

//            //计算用户与商家距离
//            Double businessLongitude = businessModel.getLongitude();
//            Double businessLatitude = businessModel.getLatitude();
//            Double number = CalculateDistance.haversine(businessLatitude, businessLongitude, latitude, longitude);
//            Double distance = Double.valueOf(String.format("%.1f", number));
//            businessModel.setDistance(distance);
            //文件id转义
            List<String> urlList = new ArrayList<>();
            String fileIdArr = businessModel.getFileId();
            if (StrUtil.isNotBlank(fileIdArr)) {
                String[] split = fileIdArr.split(",");
                for (String fileIds : split) {
                    int fileId = Integer.parseInt(fileIds);
                    FileModel fileModel = fileMapper.selectById(fileId);
                    if (fileModel != null) {
                        if (fileModel.getFileType() == 1) {
                            urlList.add(fileModel.getUrl());
                        }
                    }

                }
                businessModel.setUrlList(urlList);
            }

            QueryWrapper<ActivityModel> qw_activity = new QueryWrapper<>();
            qw_activity.eq("business_id", businessModel.getId());
            qw_activity.eq(classification!=null,"classification",classification);
            qw_activity.orderByDesc("create_time");
            List<ActivityModel> activityList = activityMapper.selectList(qw_activity);
            businessModel.setActivityList(activityList);
        }
        if (null != sort){
            if (sort == 1) {
                //距离排序
                businessList.sort(Comparator.comparing(BusinessModel::getDistance));
            }
            if (sort == 2) {
                //智能排序 距离，打分排序
                businessList.sort(Comparator.comparing(BusinessModel::getDistance));
                businessList.sort(Comparator.comparing(BusinessModel::getCreateTime).reversed());
            }
        }
        long count = businessPage.getTotal();
        BusinessVo businessVo = new BusinessVo();
        businessVo.setList(businessList);
        businessVo.setCount((int) count);
        return businessVo;
    }
    //用户查询商家列表
    @Override
    public BusinessVo getAllBusinessList(Integer page, Integer limit, String businessName, String areaId, Integer type, Double longitude, Double latitude, Integer sort, Integer classification, HttpServletRequest request) {
        Page<BusinessModel> page1 = new Page<>(page, limit);

        Page<BusinessModel> businessPage = businessMapper.getAllBusinessList(page1,businessName,type,longitude,latitude);
        List<BusinessModel> businessList = businessPage.getRecords();
        for (BusinessModel businessModel : businessList) {

//            //计算用户与商家距离
//            Double businessLongitude = businessModel.getLongitude();
//            Double businessLatitude = businessModel.getLatitude();
//            Double number = CalculateDistance.haversine(businessLatitude, businessLongitude, latitude, longitude);
//            Double distance = Double.valueOf(String.format("%.1f", number));
//            businessModel.setDistance(distance);
            //文件id转义
            List<String> urlList = new ArrayList<>();
            String fileIdArr = businessModel.getFileId();
            if (StrUtil.isNotBlank(fileIdArr)) {
                String[] split = fileIdArr.split(",");
                for (String fileIds : split) {
                    int fileId = Integer.parseInt(fileIds);
                    FileModel fileModel = fileMapper.selectById(fileId);
                    if (fileModel != null) {
                        if (fileModel.getFileType() == 1) {
                            urlList.add(fileModel.getUrl());
                        }
                    }

                }
                businessModel.setUrlList(urlList);
            }

            QueryWrapper<ActivityModel> qw_activity = new QueryWrapper<>();
            qw_activity.eq("business_id", businessModel.getId());
            qw_activity.eq(classification!=null,"classification",classification);
            qw_activity.orderByDesc("create_time");
            List<ActivityModel> activityList = activityMapper.selectList(qw_activity);
            businessModel.setActivityList(activityList);
        }
        if (null != sort){
            if (sort == 1) {
                //距离排序
                businessList.sort(Comparator.comparing(BusinessModel::getDistance));
            }
            if (sort == 2) {
                //智能排序 距离，打分排序
                businessList.sort(Comparator.comparing(BusinessModel::getDistance));
                businessList.sort(Comparator.comparing(BusinessModel::getCreateTime).reversed());
            }
        }
        long count = businessPage.getTotal();
        BusinessVo businessVo = new BusinessVo();
        businessVo.setList(businessList);
        businessVo.setCount((int) count);
        return businessVo;
    }

    //用户查询商家详情
    @Override
    public BusinessModel getUserById(Integer id, Double longitude, Double latitude, HttpServletRequest request) {
        BusinessModel businessModel = businessMapper.details(id,longitude,latitude);
        if(businessModel==null)
        {
            return null;
        }
//        //计算用户与商家距离
//        Double businessLongitude = businessModel.getLongitude();
//        Double businessLatitude = businessModel.getLatitude();
//        Double number = CalculateDistance.haversine(businessLatitude, businessLongitude, latitude, longitude);
//        Double distance = Double.valueOf(String.format("%.1f", number));
//        businessModel.setDistance(distance);

        QueryWrapper<ActivityModel> qw_activity = new QueryWrapper<>();
        qw_activity.eq("business_id", businessModel.getId());
        qw_activity.orderByDesc("create_time");
        List<ActivityModel> activityList = activityMapper.selectList(qw_activity);
        businessModel.setActivityList(activityList);

        //文件id转义
        List<String> urlList = new ArrayList<>();
        String fileIdArr = businessModel.getFileId();
        String[] split = fileIdArr.split(",");
        for (String fileIds : split) {
            int fileId = Integer.parseInt(fileIds);
            FileModel fileModel = fileMapper.selectById(fileId);
            if (fileModel != null) {
                if (fileModel.getFileType() == 1) {
                    urlList.add(fileModel.getUrl());
                }
            }

        }
        businessModel.setUrlList(urlList);
        String token = request.getHeader("token");
        if (token != null) {
            String openId = TokenUtils.verify(token);
            UserModel userModel = userService.getUserByOpenid(openId);
            if (userModel != null) {
                QueryWrapper<UserBusinessModel> qw = new QueryWrapper<>();
                qw.eq("business_id", id);
                qw.eq("user_id", userModel.getId());
                UserBusinessModel userBusiness = userBusinessMapper.selectOne(qw);
                if (userBusiness != null) {
                    businessModel.setIsCollect(1);
                } else {
                    businessModel.setIsCollect(2);
                }
            }
        }

        return businessModel;
    }

    //甄选商家活动列表
    @Override
    public BusinessVo getTranslateActivityList(Integer page, Integer limit, Double longitude, Double latitude, String businessName, Integer areaId) {
        List<BusinessModel> businessList = new ArrayList<>();
        //先查询出所有甄选活动的商家ID集合
        List<Integer> businessIdList = new ArrayList<>();
        if (StringTool.isNotEmpty(businessName)) {
            QueryWrapper<BusinessModel> businessQW = new QueryWrapper<>();
            businessQW.like("business_name", businessName);
            businessQW.eq("status", 1);
            businessQW.eq("business_status", 1);
            if (areaId != null) {
                businessQW.eq("area_id", areaId);
            }
            List<BusinessModel> businessModelList = businessMapper.selectList(businessQW);
            for (BusinessModel businessModel : businessModelList) {
                Integer id = businessModel.getId();
                businessIdList.add(id);
            }
        } else {
            if (areaId != null) {
                businessIdList = activityMapper.businessIdList(areaId);
            } else {
                businessIdList = activityMapper.TranslateBusinessIdList();
            }
        }
        for (Integer businessId : businessIdList) {
            BusinessModel businessModel = businessMapper.selectById(businessId);
            if (businessModel != null) {
                QueryWrapper<AreaModel> areaQW = new QueryWrapper<>();
                areaQW.eq("area_id", businessModel.getAreaId());
                AreaModel areaModel = areaMapper.selectOne(areaQW);
                if (areaModel != null) {
                    businessModel.setAreaText(areaModel.getArea());
                }
                //文件id转义
                List<String> urlList = new ArrayList<>();
                String fileIdArr = businessModel.getFileId();
                String[] split = fileIdArr.split(",");
                for (String fileIds : split) {
                    int fileId = Integer.parseInt(fileIds);
                    FileModel fileModel = fileMapper.selectById(fileId);
                    if (fileModel != null) {
                        if (fileModel.getFileType() == 1) {
                            urlList.add(fileModel.getUrl());
                        }
                    }

                }
                businessModel.setUrlList(urlList);

                //计算用户与商家距离
                if (businessModel.getLongitude() == null || businessModel.getLatitude() == null) {
                    businessModel.setLatitude(39.744530);
                    businessModel.setLongitude(98.510610);
                }
                Double businessLongitude = businessModel.getLongitude();
                Double businessLatitude = businessModel.getLatitude();
                Double number = CalculateDistance.haversine(businessLatitude, businessLongitude, latitude, longitude);
                Double distance = Double.valueOf(String.format("%.1f", number));
                businessModel.setDistance(distance);
                QueryWrapper<ActivityModel> qw = new QueryWrapper<>();
                qw.eq("business_id", businessId);
                qw.eq("is_pick", 1);
                qw.eq("status", 1);
                List<ActivityModel> activityList = activityMapper.selectList(qw);
                for (ActivityModel model : activityList) {
                    QueryWrapper<OrderModel> orderModelQueryWrapper = new QueryWrapper<>();
                    orderModelQueryWrapper.eq("activity_id", model.getId());
                    Integer count = orderMapper.selectCount(orderModelQueryWrapper);
                    model.setSold(count);
                }
                businessModel.setActivityList(activityList);
                businessList.add(businessModel);
            }
        }

//        businessList.sort(Comparator.comparing(BusinessModel::getLimitedTimeOffer).reversed()); //优先级最高

        BusinessVo vo = new BusinessVo();
        vo.setList(businessList);
        vo.setCount(businessIdList.size());


        return vo;
    }

        //甄选商家活动列表
    @Override
    public BusinessVo queryAndSelectMerchants(Integer page, Integer limit, Double longitude, Double latitude, String businessName, Integer areaId,Integer sort,Integer type) {

//        //先查询出所有甄选活动的商家ID集合
//            QueryWrapper<BusinessModel> businessQW = new QueryWrapper<>();
//            businessQW.like(StrUtil.isNotBlank(businessName),"business_name", businessName);
//            businessQW.eq("status", 1);
//            businessQW.eq("is_pick",1);
//            businessQW.eq(type!=null&&type>0,"type",type);
//            businessQW.eq("business_status", 1);
//            if (areaId != null) {
//                businessQW.eq("area_id", areaId);
//            }
            Integer is_pick=1;
            Page<BusinessModel> businessModelPage=new Page<>(page,limit);
            IPage<BusinessModel> businessList = businessMapper
                    .pagingQuery(
                            businessModelPage,
                            businessName,
                            is_pick,
                            type,
                            areaId,
                            longitude,
                            latitude
                            );
        for (BusinessModel businessModel : businessList.getRecords()) {
//            //计算用户与商家距离
//            Double businessLongitude = businessModel.getLongitude();
//            Double businessLatitude = businessModel.getLatitude();
//            Double number = CalculateDistance.haversine(businessLatitude, businessLongitude, latitude, longitude);
//            Double distance = Double.valueOf(String.format("%.1f", number));
//            businessModel.setDistance(distance);
            //文件id转义
            List<String> urlList = new ArrayList<>();
            String fileIdArr = businessModel.getFileId();
            if (StrUtil.isNotBlank(fileIdArr)) {
                String[] split = fileIdArr.split(",");
                for (String fileIds : split) {
                    int fileId = Integer.parseInt(fileIds);
                    FileModel fileModel = fileMapper.selectById(fileId);
                    if (fileModel != null) {
                        if (fileModel.getFileType() == 1) {
                            urlList.add(fileModel.getUrl());
                        }
                    }

                }
                businessModel.setUrlList(urlList);
            }
        }
        if (null != sort){
            if (sort == 2) {
                businessList.getRecords().sort(Comparator.comparing(BusinessModel::getIsPick).reversed());
            }
        }
        BusinessVo vo = new BusinessVo();
        vo.setList(businessList.getRecords());
        vo.setCount((int) businessList.getTotal());
        return vo;
    }




    //商家经营数据
    @Override
    public BusinessDataVo getBusinessData(Integer userId) {
        String dayDate = CommonHelp.getNowDate();
        String monthDate = dayDate.substring(0, 7);
        String beginTimeDay = dayDate + " 00:00:00";
        String endTimeDay = dayDate + " 23:59:59";
        String beginTimeMonth = monthDate + "-01 00:00:00";
        BusinessDataVo businessDataVo = new BusinessDataVo();
        UserModel userModel = userMapper.selectById(userId);
        QueryWrapper<BusinessModel> businessModelQueryWrapper = new QueryWrapper<>();
        businessModelQueryWrapper.eq("user_phone", userModel.getPhone());
        BusinessModel businessModel = businessMapper.selectOne(businessModelQueryWrapper);
        if (businessModel != null) {
            Integer businessId = businessModel.getId();
            //我的收益
            Double sumIncome = orderMapper.sumIncome(businessId, userId);
            if (sumIncome == null) {
                sumIncome = 0.0;
            }
            Double incomeDay = orderMapper.incomeTime(beginTimeDay, endTimeDay, businessId, userId);
            if (incomeDay == null) {
                incomeDay = 0.0;
            }
            Double incomeMonth = orderMapper.incomeTime(beginTimeMonth, endTimeDay, businessId, userId);
            if (incomeMonth == null) {
                incomeMonth = 0.0;
            }
            businessDataVo.setIncome(sumIncome);
            businessDataVo.setIncomeDay(incomeDay);
            businessDataVo.setIncomeMonth(incomeMonth);
            //我的订单
            QueryWrapper<OrderModel> orderQW = new QueryWrapper<>();
            orderQW.eq("user_id", userId);
            orderQW.eq("business_id", businessId);
            orderQW.last("AND (status=2 or status =3)");
            Integer sumOrder = orderMapper.selectCount(orderQW);
            if (sumOrder == null) {
                sumOrder = 0;
            }
            Integer orderDay = orderMapper.orderTime(beginTimeDay, endTimeDay, businessId, userId);
            if (orderDay == null) {
                orderDay = 0;
            }
            Integer orderMonth = orderMapper.orderTime(beginTimeMonth, endTimeDay, businessId, userId);
            if (orderMonth == null) {
                orderMonth = 0;
            }
            businessDataVo.setOrder(sumOrder);
            businessDataVo.setOrderDay(orderDay);
            businessDataVo.setOrderMonth(orderMonth);
        }
        //我的推广
        QueryWrapper<InviteRecordModel> inviteRecordQW = new QueryWrapper<>();
        inviteRecordQW.eq("invite_id", userId);
        Integer sumPromotion = inviteRecordMapper.selectCount(inviteRecordQW);
        if (sumPromotion == null) {
            sumPromotion = 0;
        }
        Integer promotionDay = inviteRecordMapper.promotionTime(beginTimeDay, endTimeDay, userId);
        if (promotionDay == null) {
            promotionDay = 0;
        }
        Integer promotionMonth = inviteRecordMapper.promotionTime(beginTimeMonth, endTimeDay, userId);
        if (promotionMonth == null) {
            promotionMonth = 0;
        }
        businessDataVo.setPromotion(sumPromotion);
        businessDataVo.setPromotionDay(promotionDay);
        businessDataVo.setPromotionMonth(promotionMonth);
        businessDataVo.setVoucher(userModel.getVoucher());
        return businessDataVo;
    }


    @Override
    public BusinessModel getByUserPhone(String phone) {
        QueryWrapper<BusinessModel> businessModelQueryWrapper = new QueryWrapper<>();
        businessModelQueryWrapper.eq("user_phone", phone);
        return businessMapper.selectOne(businessModelQueryWrapper);
    }

    /**
     * 访问业务数据
     *
     * @param userId 用户id
     * @return {@link Map}<{@link String},{@link Object}>
     */
    @Override
    public Map<String, Integer> accessToBusinessData(Integer userId) {
        return this.businessMapper.accessToBusinessData(userId);
    }

    @Override
    public Map<String, Integer> selectCount(Integer userId) {
        return this.businessMapper.selectViewCount(userId);

    }

    @Override
    public void businessGrant(Integer id, Double voucherAmount, Double integral) {
        BusinessModel model = businessMapper.selectById(id);
        if (model != null) {
            QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<>();
            userModelQueryWrapper.eq("phone", model.getUserPhone());
            UserModel userModel = userMapper.selectOne(userModelQueryWrapper);
            if (voucherAmount != null) {
                userModel.setVoucher(userModel.getVoucher() + voucherAmount);
            } else {
                voucherAmount = 0.0;
            }
            if (integral != null) {
                userModel.setIntegral(userModel.getIntegral() + integral);
            } else {
                integral = 0.0;
            }
            userMapper.updateById(userModel);
            DistributionRecord distributionRecord = new DistributionRecord();
            VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
            if (voucherAmount > 0) {
                //增加益联券记录
                voucherRecordModel.setName("益联券发放");
                voucherRecordModel.setTypeName("益联券发放");
                String amountVoucher = "+" + voucherAmount + "券";
                voucherRecordModel.setVoucher(amountVoucher);
                voucherRecordModel.setUserId(userModel.getId());
                voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                voucherRecordModel.setVoucherType(1);
                voucherRecordModel.setVoucherAmount(voucherAmount);
                voucherRecordMapper.insert(voucherRecordModel);
                //消息盒子记录数据
                MessageBoxModel messageBoxModel = new MessageBoxModel();
                messageBoxModel.setUserId(userModel.getId());
                messageBoxModel.setQuiltUserId(userModel.getId());
                messageBoxModel.setTypeName("到账通知");
                messageBoxModel.setVoucher(voucherAmount);
                messageBoxModel.setNotes("益联券发放");
                messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
                messageBoxMapper.insert(messageBoxModel);
                distributionRecord.setAmount(BigDecimal.valueOf(voucherAmount));
                distributionRecord.setAmountDistributionType(1);
            } else if(voucherAmount<0) {
                //增加益联券记录
                voucherRecordModel.setName("益联券扣减");
                voucherRecordModel.setTypeName("益联券扣减");
                String amountVoucher = voucherAmount + "券";
                voucherRecordModel.setVoucher(amountVoucher);
                voucherRecordModel.setUserId(userModel.getId());
                voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                voucherRecordModel.setVoucherType(0);
                voucherRecordModel.setVoucherAmount(voucherAmount);
                voucherRecordMapper.insert(voucherRecordModel);
                //消息盒子记录数据
                MessageBoxModel messageBoxModel = new MessageBoxModel();
                messageBoxModel.setUserId(userModel.getId());
                messageBoxModel.setQuiltUserId(userModel.getId());
                messageBoxModel.setTypeName("扣减通知");
                messageBoxModel.setVoucher(voucherAmount);
                messageBoxModel.setNotes("益联券扣减");
                messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
                messageBoxMapper.insert(messageBoxModel);
                distributionRecord.setAmount(BigDecimal.valueOf(voucherAmount));
                distributionRecord.setAmountDistributionType(2);
            }
            IntegralRecordModel integralRecordModel = new IntegralRecordModel();
            if (integral > 0) {
                //增加积分记录
                integralRecordModel.setName("积分发放");
                integralRecordModel.setTypeName("发放");
                String amountIntegral = "+" + integral + "分";
                integralRecordModel.setIntegral(amountIntegral);
                integralRecordModel.setUserId(userModel.getId());
                integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                integralRecordModel.setVoucherType(1);
                integralRecordModel.setVoucherAmount(integral);
                integralRecordService.save(integralRecordModel);
                distributionRecord.setIntegral(BigDecimal.valueOf(integral));
                distributionRecord.setIntegralDistributionType(1);
            } else if(integral<0) {
                //增加积分记录
                integralRecordModel.setName("积分扣减");
                integralRecordModel.setTypeName("扣减");
                String amountIntegral = integral + "分";
                integralRecordModel.setIntegral(amountIntegral);
                integralRecordModel.setUserId(userModel.getId());
                integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
                integralRecordModel.setVoucherType(0);
                integralRecordModel.setVoucherAmount(integral);
                integralRecordService.save(integralRecordModel);
                distributionRecord.setIntegral(BigDecimal.valueOf(integral));
                distributionRecord.setIntegralDistributionType(2);
            }
            //增加发放记录
            distributionRecord.setBusinessId(id);
            distributionRecord.setUserId(userModel.getId());
            distributionRecord.setType(1);
            distributionRecord.setDistributionTime(CommonHelp.getNowTimestamp());
            distributionRecord.setCreateTime(CommonHelp.getNowTimestamp());
            distributionRecordsMapper.insert(distributionRecord);
        }
    }


    /**
     * 判断该商家是否已入住
     *
     * @param userphone 绑定入驻表和管理表的唯一字段
     * @return
     */
    @Override
    public BusinessModel getBusinessByUserPhone(String userphone) {
        BusinessModel businessModel = businessMapper.selectByUserPhone(userphone);
        return businessModel;
    }

    @Override
    public List<BusinessModel> selectbusinessList(List<Integer> list) {
        List<BusinessModel> businessModelList = businessMapper.selectBatchIds(list);
        return businessModelList;
    }
}
